package com.zhihaoliang.coroutine.buss.channel.func

import com.zhihaoliang.coroutine.util.log
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

/**
 * @author 支豪亮
 * @date 2022/10/28 09:15
 * @des 设置 Buffer
 */
object ChannelBuffer {

    fun sendWithBuffer(mainScope:CoroutineScope) = mainScope.launch {
        val channel = Channel<Int>(4) // create buffered channel
        val sender = launch { // launch sender coroutine
            repeat(10) {
                log("Four Sending $it") // print before sending each element
                channel.send(it) // will suspend when buffer is full
            }
        }
        // don't receive anything... just wait....
        delay(1000)
        sender.cancel() // cancel sender coroutine

        val channel1 = Channel<Int>(2) // create buffered channel
        val sender1 = launch { // launch sender coroutine
            repeat(10) {
                log("Two Sending $it") // print before sending each element
                channel1.send(it) // will suspend when buffer is full
            }
        }
        // don't receive anything... just wait....
        delay(1000)
        sender1.cancel() // cancel sender coroutine
    }
}